package com.ruoyi.jnpfjava.controller;

import com.ruoyi.jnpfjava.entity.AjaxResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/updateFile")
public class helloController {
    private static final String FILE_DIRECTORY = "D:\\soft\\upload\\";

    @GetMapping("hello")
    public String hello() {
        return "Hello World!";
    }


    @PostMapping
    public AjaxResult updateFile(@RequestParam("image") MultipartFile multipartFile) {
//        System.out.println(file.getOriginalFilename());
        if (multipartFile.isEmpty()){
            return AjaxResult.error("文件为空");
        }
        try {
            String fileName = multipartFile.getOriginalFilename();
            System.out.println(fileName);
            // 获取文件并保存
            byte[] bytes = multipartFile.getBytes();
            Path path = Paths.get(FILE_DIRECTORY + multipartFile.getOriginalFilename());
            System.out.println(path);
            Files.write(path, bytes);
            FilePath filePath = new FilePath();
            filePath.setFileName(fileName);
            filePath.setPath(path.toAbsolutePath().normalize().toString());
            return AjaxResult.success("文件上传成功",filePath);
        } catch (RuntimeException e) {
            return AjaxResult.error("文件上传失败");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
